#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author  : config_spider
import math

import scrapy
import re
from apps.tax_policy.tax_policy.items import NetTaxPolicyItem as Item, urllib, time
from apps.tax_policy.tax_policy.spiders.base_spider.base_tax_policy_spider import BaseTaxPolicySpider


class HenanZhoukouPolicy(BaseTaxPolicySpider):
    name = 'henan_zhoukou_sitesources2_policy'
    
    province = '河南省'
    city = '周口市'
    # county = '滑县'
    park = ''

    def start_requests(self):
        for source, county, url in [
            ['周口市太康县人民政府', "太康县", "http://www.taikang.gov.cn/sitesources/tkx/page_pc/zwgk/zc/xzgfxwj/list1.html"],
            ['周口市太康县人民政府', "太康县", "http://www.taikang.gov.cn/sitesources/tkx/page_pc/zwgk/zfxxgkml/zfwj/list1.html"],
            ['周口市太康县人民政府', "太康县", "http://www.taikang.gov.cn/sitesources/tkx/page_pc/zwgk/zfxxgkml/zfbwj/list1.html"],
            ['周口市西华县人民政府', "西华县", "http://www.xihua.gov.cn/sitesources/xhxrmzf/page_pc/zfxxgkpt/zc/xzgfxwj/list1.html"],
            ['周口市西华县人民政府', "西华县", "http://www.xihua.gov.cn/sitesources/xhxrmzf/page_pc/zfxxgkpt/fdzdgknr/zcwj/list1.html"],
            ['周口市项城市人民政府', "项城市", "http://www.xiangcheng.gov.cn/sitesources/xcs/page_pc/xxgk/jcxxgk/zfwj/xz/list1.html"],
            ['周口市项城市人民政府', "项城市", "http://www.xiangcheng.gov.cn/sitesources/xcs/page_pc/xxgk/jcxxgk/zfwj/xzb/list1.html"],
            ['周口市项城市人民政府', "项城市", "http://www.xiangcheng.gov.cn/sitesources/xcs/page_pc/xxgk/jcxxgk/zfwj/xzgfxwj/list1.html"],
            ['周口市发展和改革委员会', "", "http://fgw.zhoukou.gov.cn/sitesources/fzggwyh/page_pc/zfxxgkpt/zc/xzgfxwj/list1.html"],
            ['周口市工业和信息化局', "", "http://gxj.zhoukou.gov.cn/sitesources/gyxxhj/page_pc/zwgk/zc/xzgfxwj/list1.html"],
            ['周口市科学技术局', "", "http://kjj.zhoukou.gov.cn/sitesources/kjj/page_pc/zwgk/zc/xzgfxwj/list1.html"],
            ['周口市人力资源和社会保障局', "", "http://rsj.zhoukou.gov.cn/sitesources/zkrlzyhshbzj/page_pc/zwgk/zcwj/list1.html"],
            ['周口市住房和城乡建设局', "", "http://zfcxjs.zhoukou.gov.cn/sitesources/zfcxjsj/page_pc/zwgk/zc/xzgfxwj/list1.html"],
            ['周口市农业农村局', "", "http://nyncj.zhoukou.gov.cn/sitesources/nyncj/page_pc/zwgk/fdzdgknr/zcwj/xzgfxwj/list1.html"],
            ['周口市商务局', "", "http://swj.zhoukou.gov.cn/sitesources/swj/page_pc/zfxxgk/zc/xzgfxwj/list1.html"],
            ['周口市市场监督管理局', "", "http://scjg.zhoukou.gov.cn/sitesources/scjdglj/page_pc/zfxxgkpt/zc/xzgfxwj/index.html"],
            ['周口市人民政府', "", "http://www.zhoukou.gov.cn/page_pc/zwgk/zdxxgk/zfwj/zz/list1.html"],
            ['周口市人民政府', "", "http://www.zhoukou.gov.cn/page_pc/zwgk/zdxxgk/zfwj/zzb/list1.html"],
        ]:
            item = {'source': source, 'county': county}
            yield scrapy.Request(url, callback=self.parse_list, meta={'item': item}, dont_filter=True)

    def parse_list(self, response, **kwargs):
        prev_item = response.meta.get('item')
        elem_list = response.xpath(
            "//div[@class='colRightOne' or @class='msg_li' or @class='hap_infoOne']//a[(contains(@href, '.htm') or @title)]/parent::div[string-length(string(.))>=10] | "
            "//ul//li[@class='colRightOne']//a[(contains(@href, '.htm') or @title)]/parent::li[string-length(string(.))>=10] | "
            "//tr[@class]//td//a[(contains(@href, '.htm') or @title)]/parent::td[string-length(string(.))>=10] | "
            "//ul[contains(@class, 'ul ULLIST') or @class='infoList']//li//a[@class]/ancestor::li[string-length(string(.))>=10]"
        )
        # if not elem_list:
        #     yield response.follow(response.url, callback=self.parse_list, meta={'item': prev_item}, dont_filter=True)
        #     return
        for elem in elem_list:
            item = Item()
            item['source_url'] = elem.xpath(""".//a/@href""").get()
            item['source_url'] = response.urljoin(item['source_url'])
            item['publish_date'] = elem.xpath("""string(.)""").get()
            if prev_item is not None:
                for key, value in prev_item.items():
                    item[key] = value
            if not item['source_url']:
                continue
            # if '.htm' not in item['source_url'] and '.shtm' not in item['source_url']:
            #     continue
            if 'relativeInfo' in item['source_url']:
                continue
            print(response.url, item['source_url'])
            cookies = {
                "zh_choose": 'n'
            }
            yield response.follow(item['source_url'], callback=self.parse_detail, meta={'item': item}, cookies=cookies)
        if response.meta.get("is_next") is not False:
            r"scriptJsonPath\s*=\s*[\"'](.*?)[\"']"
            url = response.xpath(""".""").re_first(r'scriptJsonPath\s*=\s*["\'](.*?)["\']') or response.xpath(""".""").re_first(r'JSON.*\(["\'](.*?)["\']')
            if not url:
                return
            yield response.follow(url, callback=self.parse_page, meta={'item': prev_item, 'is_next': False, "url": response.url})

    def parse_page(self, response, **kwargs):
        total_page = response.json()['endPage']
        print(response.url, "page:", total_page)
        for page_num in range(2, int(total_page) + 1):
            if page_num <= response.json()['pageNum']:
                url = response.meta['url'].replace("list1", f"list{page_num}")
            else:
                url = f'/template/viewCatalogList?catalogId={response.json()["catalogId"]}&page={page_num}'

            yield response.follow(url, callback=self.parse_list, meta=response.meta)

    def parse_detail(self, response, **kwargs):
        item = Item() if response.meta.get('item') is None else response.meta.get('item')
        item['title'] = response.xpath("""string(//meta[@name='ArticleTitle']/@content)""").get()
        item['publish_date'] = response.xpath("//*[contains(.//text(), '发布日期：') or contains(.//text(), '发布时间：')]//text()").re_first(r"(\d{4}-\d{1,2}-\d{1,2})")
        # print(item['publish_date'])
        item['content'] = response.xpath(""".""").get()
        # item['source'] = self.source
        # print(item['content'])
        item['province'] = self.province
        item['city'] = self.city
        # item['county'] = self.county
        item['park'] = self.park
        yield item


if __name__ == "__main__":
    from scrapy import cmdline

    cmdline.execute("scrapy crawl henan_zhoukou_sitesources2_policy".split())
